package fule.com.webviewdemo.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;

import fule.com.webviewdemo.R;

/**
 * 作者： njb
 * 时间： 2018/7/10 0010-上午 10:29
 * 描述： webView加载img标签
 * 来源：
 */
public class WebViewActivity extends AppCompatActivity {
    private WebView webView;
    private String content;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        initView();
    }

    private void initView() {
        webView = findViewById(R.id.webview);
        content = "<p> <img class=\"wscnph\" src=\"https://as-ssm.oss-cn-shanghai.aliyuncs.com/backend/goods/20220309/YEs7KE38KKHEhTBR.jpg\" /></p >";
        String linkCss = "<style type=\"text/css\"> " +
                "img {" +
                "width:100%;" +
                "height:auto;" +
                "}" +
                "</style>";

        String html = "<html><header>" + linkCss + "</header>" + content + "</body></html>";
        webView.loadData(getHtmlData(content), "text/html", "UTF-8");
    }

    /**
     * 添加img标签自适应图片宽高方法
     * @param bodyHTML
     * @return
     */
    public static String getHtmlData(String bodyHTML) {
        String head = "<head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> <style>img{max-width: 100%; width:100%; height:auto;}</style> </head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }
}
